package main

import "C"
import (
	"fmt"
	"gitee.com/hakwolf/dbmagic/golib/internal/models"
	"gitee.com/hakwolf/dbmagic/golib/internal/modules/configdbg"
	sqldriver2 "gitee.com/hakwolf/dbmagic/golib/internal/sqldriver"
	"strconv"
	"unsafe"
)

//export InitCliModule
func InitCliModule() {
	// 初始化DB
	models.Db = models.CreateSqliteDb()
	fmt.Println("欢迎使用：备无患-数据库备份引擎")

	//创建数据库表
	climigration := new(models.CliMigration)
	err := climigration.Install("")
	if err != nil {
		//return json.CommonFailure(fmt.Sprintf("创建数据库表失败-%s", err.Error()), err)
		configdbg.Println("创建数据库表失败-%s")
	}
}

//export GetSqlLiteDbConn
func GetSqlLiteDbConn(filename *C.char) C.struct_ResultInfo {
	//func Test(dbinfo *C.struct_DbInfo) *C.struct_ResultInfo {
	//var
	//cStruct.field1 = 10
	//cString := C.CString("Hello from C")
	//cStruct.field2 = (*C.char)(cString)

	//fmt.Printf("Field1: %d\n", cStruct.field1)
	//fmt.Printf("Field2: %s\n", C.GoString(dbinfo.server))
	//server := C.GoString(dbinfo.server) //C.GoString(dbinfo.server)
	//gouser := C.GoString(dbinfo.user)
	//pwd := C.GoString(dbinfo.pwd)
	//godb := C.GoString(dbinfo.db)
	//goport := int(dbinfo.port)

	sqldb, err := sqldriver2.GetSqlliteDB(C.GoString(filename))
	if err == nil {
		//code = C.CString(err.Error())
		//fmt.Println(sqldb)
		ptr := unsafe.Pointer(sqldb)
		// 将结构体地址转换为整型
		addr := uintptr(ptr)

		return C.struct_ResultInfo{strId: C.CString(strconv.Itoa(int(addr))), ers: C.CString("nil")} //, C.CString()

	} else {
		str := C.CString(err.Error())
		return C.struct_ResultInfo{strId: C.CString(strconv.Itoa(int(0))), ers: str} //, C.CString()
		//code = &Retinfo
		//return code
	}
}

func main2() {
	//var dbinfo C.struct_DbInfo
	//dbinfo.server = C.CString("127.0.0.1")
	//dbinfo.user = C.CString("sa")
	//dbinfo.pwd = C.CString("sql")
	//dbinfo.db = C.CString("testdb")
	//dbinfo.port = C.int(3688)

	//var lna C.struct_ResultInfo
	//GetSqlDbConn(1, &lna)
	//fmt.Println("")
	//fmt.Println("id" + C.GoString(lna.strId))
	//fmt.Println("user =" + C.GoString(lna.ers))
	//if C.GoString(lna.ers) == "nil" {
	//	var lnb C.struct_ResultInfo
	//	ProcessQuery(lna.strId, C.CString("SELECT * FROM tb_aa"), &lnb)
	//	fmt.Println("rowid" + C.GoString(lnb.strId))
	//	fmt.Println("rowuser =" + C.GoString(lnb.ers))
	//	if C.GoString(lnb.ers) == "nil" {
	//		RowNext(lnb.strId)
	//		RowNext(lnb.strId)
	//	}
	//} else {
	//	fmt.Println("连接失败！")
	//}

	//fmt.Println(lna)
	//var cStruct C.struct_MyStruct
	//cStruct.field1 = 10
	//cString := C.CString("Hello from C")
	//cStruct.field2 = (*C.char)(cString)
	//
	//fmt.Printf("Field1: %d\n", cStruct.field1)
	//fmt.Printf("Field2: %s\n", C.GoString(cStruct.field2))

	//// 使用Go结构体查看字段
	//var goStruct MyStruct = MyStruct{
	//	field1: cStruct.field1,
	//	field2: cStruct.field2,
	//}

	//fmt.Printf("Field1: %d\n", goStruct.field1)
	//fmt.Printf("Field2: %s\n", C.GoString(goStruct.field2))

	// 清理C分配的内存
	//C.free(unsafe.Pointer(cString))

}
